<?php
/**
 * Created by PhpStorm.
 * User: lili
 * Date: 2018/11/22
 * Time: 21:29
 */

namespace app\admin\controller;


use app\admin\model\Check;
use app\index\model\Baseinsulin;
use app\index\model\Beginningtreatment;
use app\index\model\Item;
use app\index\model\Reason;
use app\index\model\Sulintime;
use app\index\model\User;
use think\Db;
use Tools\Utf8ToPinyin;

class Treat extends Common
{



    protected $beforeActionList = [
        'one' => ['only'=>'treatlist,treatment,addtreatment'],
        'tow' => ['only'=>'blood,blooddetail']  ,
        'three' => ['only'=>'beforeeating,beforeeatingdetail']  ,
        'forth' => ['only'=>'temporary,temporarydetail']  ,
        'six' => ['only'=> 'history,bshistory']
    ];

    protected function one()
    {
        $this->assign('t',1);

    }

    protected function tow()
    {
        $this->assign('t',2);

    }

    protected function three()
    {
        $this->assign('t',3);

    }
    
    protected function forth(){
        $this->assign('t',4);
    }

    protected function six(){
        $this->assign('t',6);
    }


    /*
     * 起始治疗方案列表页面
     *
     * */

    public function treatlist(){
        return $this->fetch();
    }


    /*
     * 起始治疗方案列表页面
     *
     * */

    public function treatlistjson(){

        $send = input();
//        dump($send);
       /* array(3) {
            ["page"] =&gt; string(1) "1"
            ["limit"] =&gt; string(2) "10"
            ["key"] =&gt; array(1) {
                ["id"] =&gt; string(1) "1"
          }
        }*/
        $page = empty($send['page'])?1:$send['page'];
        $limit = empty($send['limit'])?10:$send['limit'];
        $key = empty($send['key'])? '':$send['key'];
        $w = array();
        if(!empty($key['hospital'])){
            $w['hospital'] = $key['hospital'];
        }
        if(!empty($key['uid'])){
            $w['b.uid'] = $key['uid'];
        }
        if(!empty($key['insulin'])){
            $w['insulin'] = $key['insulin'];
        }

        if(!empty($key['username'])){
            $w['username'] =  ['like','%'.$key['username'].'%'] ;
        }

        $btmodel = new Beginningtreatment();
        $btlist = $btmodel->getAllBTs($page,$limit,$w);
        foreach ($btlist as $i => $v){
            switch($v['insulin']){
                case 1:$btlist[$i]['insulin'] = '速效胰岛素（超短效胰岛素）';break;
                case 2:$btlist[$i]['insulin'] = '短效胰岛素（常规胰岛素）';break;
                default:$btlist[$i]['insulin'] = '速效胰岛素（超短效胰岛素）';
            }
            //$btlist[$i]['username'] = $v['user']['username'];
        }
        $count = $btmodel->getBTsCount($w);
        $resjson = '{ "code": 0, "msg": "","count": '.$count.', "data":'.json_encode($btlist) .'}';
        echo $resjson;
    }





    /*
     * 获得起始治疗方案
     * @param int uid 用户id
     *
     *
     * */
    public function treatment(){
        $uid = input('uid');
        if(empty($uid)){
            $this->error("uid不可以为空");
        }
        $btmodel = new Beginningtreatment();
        $res = $btmodel->with('user')->where('uid',$uid)->find();
//        dump($res->user->toArray());
        $this->assign('treatment',$res);

        return $this->fetch();

    }





    /*
     * 增加起始治疗方案
     *
     *
     * */
    public function addtreatment(){

        if (request()->isPost()){

            $send = input('post.','','htmlspecialchars,strip_tags,trim');
//            dump($send);
            $btv = new \app\index\validate\Beginningtreatment();
            if ($btv->check($send)){
                $uid = $send['uid'];
                $btmodel = new Beginningtreatment();
                $w['uid'] = $uid;

                $usermodel = new User();
                if($usermodel->isUser($w)){
                    if ($btmodel->isHaving($w)){
                        //存在更新

                        $res = $btmodel->isUpdate(true)->save($send,[
                            'uid' => $uid
                        ]);
                        if($res!=false){
                            $bimodel = new Baseinsulin();
                            $bimodel->insertbaseinsulin($uid,$send['baseinsulin'],time());//插入基础率总量修改记录
                            $stmodel = new Sulintime();
                            $stmodel->insertSulintime($uid,$send['sulin0003'],$send['sulin0307'],$send['sulin0712'],$send['sulin1217'],$send['sulin1722'],$send['sulin2224'],time());//插入总量修改记录
                            $this->success('更新成功');

                        }
                    }else{
                        //增加
                        $res = $btmodel->isUpdate(false)->save($send);
                        if($res!=false){
                            $bimodel = new Baseinsulin();
                            $bimodel->insertbaseinsulin($uid,$send['baseinsulin'],time());//插入基础率总量修改记录
                            $stmodel = new Sulintime();
                            $stmodel->insertSulintime($uid,$send['sulin0003'],$send['sulin0307'],$send['sulin0712'],$send['sulin1217'],$send['sulin1722'],$send['sulin2224'],time());//插入修改记录
                            $this->success('增加成功');
                        }
                    }
                }else{
                    $this->error('不存在这个用户');
                }

            }else{
                $this->error($btv->getError());
            }
        }else{
            $this->error('必须post请求');
        }

    }


    /*
         * 删除起始治疗方案
         *
         * */
    public function delete(){
        $send = input();
//        dump($send);
        Db::startTrans();
        try{
            $btmodel = new Beginningtreatment();
            $btmodel->destroy($send['brid']);//

            // 提交事务
            Db::commit();

        } catch (\Exception $e) {
            // 回滚事务
//            dump($e);
            Db::rollback();
            $this->error('删除失败');

        }

        $this->success('删除成功');

    }



    /*
     * 血糖监测页面
     *
     *
     * */
    public function blood(){
        
        $item = new Item();
        $itemlist = $item->where('pid',1)->select();
        
        $this->assign('itemlist',$itemlist);
        return $this->fetch();
    }
    
    /*
     * 血糖列表json
     * 
     * */
    public function bloodlistjson(){


        $send = input();
        $page = empty($send['page'])?1:$send['page'];
        $limit = empty($send['limit'])?10:$send['limit'];
        
        //搜索条件
        $key = empty($send['key'])? '':$send['key'];
        $w = array();
        if(!empty($key['username'])){
            $w['username'] =  ['like','%'.$key['username'].'%'] ;
        }
        if(!empty($key['date'])){
            $time1 = strtotime($key['date']);
            $time2 = strtotime('+1day',$time1);
            $w['date'] =['between',[date('Y-m-d',$time1),date('Y-m-d',$time2)]] ;
        }
        if(!empty($key['itemid'])){
            $w['itemid'] =['like','%'.$key['itemid']] ;
        }
        if(!empty($key['health'])){
            $w['health'] = $key['health'];
        }
        if(!empty($key['type'])){
            $w['type'] = $key['type'];
        }


        
        
        
        $checkmodel = new Check();
        $checklist = $checkmodel->getBloodSugarCheck($page,$limit,$w);
        $w2['itemid'] = ['like','1%'];
        $count = $checkmodel
            ->alias('c')
            ->join('__USER__ u ','c.uid = u.uid')
            ->where($w)
            ->where($w2)
            ->count();



        $resjson = '{ "code": 0, "msg": "","count": '.$count.', "data":'.json_encode($checklist) .'}';
        echo $resjson;

        exit();
    }


    /*
     * 血糖的详细页面
     *
     *
     * */
    public function blooddetail(){
        $send = input();
        $cid = $send['cid'];
        $checkmodel = new Check();
        $bdres = $checkmodel->getBloodCheck($cid);



        //血糖不正常原因
        $reasonmodel = new Reason();
        if ( !empty($bdres['reasonid']) ){
            $reasonlist = $reasonmodel->where('rid','in',$bdres['reasonid'])->select();
            $bdres['reasonlist'] = $reasonlist;
        }
//        dump($bdres);
        $this->assign('bd',$bdres);
        $item = new Item();
        $itemlist = $item->where('pid',1)->select();

        $this->assign('itemlist',$itemlist);




        return $this->fetch();

    }

    /*
     *餐前大剂量列表 
     * 
     * */
    public function beforeeating(){
        $item = new Item();
        $itemlist = $item->where('pid',2)->select();

        $this->assign('itemlist',$itemlist);
        return $this->fetch();
    }


    /*
     * 餐前大剂量列表json
     * */
    public function beforeeatinglistjson(){
        $send = input();
        $page = empty($send['page'])?1:$send['page'];
        $limit = empty($send['limit'])?10:$send['limit'];





        //搜索条件
        $key = empty($send['key'])? '':$send['key'];
        $w = array();
        if(!empty($key['username'])){
            $w['username'] =  ['like','%'.$key['username'].'%'] ;
        }
        if(!empty($key['date'])){
            $time1 = strtotime($key['date']);
            $time2 = strtotime('+1day',$time1);
            $w['date'] =['between',[date('Y-m-d',$time1),date('Y-m-d',$time2)]] ;
        }
        if(!empty($key['itemid'])){
            $w['itemid'] =['like','%'.$key['itemid']] ;
        }
    
        
        
        
        
        
        
        
        $checkmodel = new Check();
        $checklist = $checkmodel->getbeforeeatingChecklist($page,$limit,$w);
        $w2['itemid'] = ['like','2%'];
        $count = $checkmodel
            ->alias('c')
            ->join('__USER__ u ','c.uid = u.uid')
            ->where($w)
            ->where($w2)
            ->count();;


        $resjson = '{ "code": 0, "msg": "","count": '.$count.', "data":'.json_encode($checklist) .'}';
        echo $resjson;
        exit();
    }


    /*
     * 大剂量详细页
     *
     * */
    public function beforeeatingdetail(){
        $send = input();
        $cid = $send['cid'];
        $checkmodel = new Check();
        $bdres = $checkmodel->getbeforeeatingCheck($cid);
        $this->assign('bd',$bdres);

        $item = new Item();
        $itemlist = $item->where('pid',2)->select();

        $this->assign('itemlist',$itemlist);

        return $this->fetch();
    }

    /*
     * 临时大剂量
     *
     *
     * */
    public function temporary(){
        return $this->fetch();
    }

    /*
     * 临时大剂量json
     * */
    public function temporarylistjson(){
        $send = input();
        $page = empty($send['page'])?1:$send['page'];
        $limit = empty($send['limit'])?10:$send['limit'];


        //搜索条件
        $key = empty($send['key'])? '':$send['key'];
        $w = array();
        if(!empty($key['username'])){
            $w['username'] =  ['like','%'.$key['username'].'%'] ;
        }
        if(!empty($key['date'])){
            $time1 = strtotime($key['date']);
            $time2 = strtotime('+1day',$time1);
            $w['date'] =['between',[date('Y-m-d',$time1),date('Y-m-d',$time2)]] ;
        }
         
        
        
        $checkmodel = new Check();
        $checklist = $checkmodel->gettemporaryChecklist($page,$limit,$w);
        $w2['itemid'] = ['like','3%'];
        $count = $checkmodel->alias('c')
            ->join('__USER__ u ','c.uid = u.uid')
            ->where($w)
            ->where($w2)
            ->count();;


        $resjson = '{ "code": 0, "msg": "","count": '.$count.', "data":'.json_encode($checklist) .'}';
        echo $resjson;
        exit();
    }


    /*
     * 临时大剂量详细页
     *
     * */
    public function temporarydetail(){
        $send = input();
        $cid = $send['cid'];
        $checkmodel = new Check();
        $bdres = $checkmodel->gettemporaryCheck($cid);
        $this->assign('bd',$bdres);
        return $this->fetch();
    }


    /*
     *血糖监测删除或者胰岛素剂量删除
     *
     * */
    public function checkdelete(){
        $send = input();
//        dump($send);
        Db::startTrans();
        try{
            $checkmodel = new Check();
            $checkmodel->destroy($send['cid']);//

            // 提交事务
            Db::commit();

        } catch (\Exception $e) {
            // 回滚事务
//            dump($e);
            Db::rollback();
            $this->error('删除失败');

        }

        $this->success('删除成功');
    }
    
    
    
    /*
     * 历史数据汇总记录
     * 
     * 
     * */
    public function history(){
        $uid = input('uid');
        $date = input('date');
        if(empty($uid)){
            $this->error('uid不可以为空');
        }
        if (empty($date)){
            $date = date('Y-m-d');
        }

        $btmodel = new Beginningtreatment();
        $checkmodel = new \app\index\model\Check();
        $res = $btmodel->where('uid',$uid)->find();
        $baseinsulinDate = $res['baseinsulin'];//基础率总量
        $beforeeatinsulinDate = $checkmodel->getbeforeeatinsulinOfDate($uid,$date);//历史记录的餐前大剂量总量
        $temporaryinsulinDate = $checkmodel->gettemporaryinsulinOfDate($uid,$date);//历史记录的临时大剂量总量
        $temporaryinsulinlistDate = $checkmodel->gettemporaryinsulinListOfDate($uid,$date);//历史记录的临时大剂量列表
//        dump($temporaryinsulinlistDate);
        $insulinDate = $baseinsulinDate + $beforeeatinsulinDate + $temporaryinsulinDate;//历史记录的总量

        //大剂量的值
        $insulindatearr = array(
            'baseinsulindate' => $baseinsulinDate,
            'beforeeatinsulindate' => $beforeeatinsulinDate,
            'temporaryinsulindate' => $temporaryinsulinDate,
            'temporaryinsulinlistdate' => $temporaryinsulinlistDate,
            'insulindate' => $insulinDate

        );
//        dump($insulindatearr);

        //血糖
        $checkmodel = new \app\index\model\Check();
        $bsres = $checkmodel->getBloodSugarCheckOfDate($uid, $date);//血糖的列表


        //用户信息
        $usermodel = new \app\admin\model\User();
        $user = $usermodel->getUserByuid($uid);




        $this->assign('insulin',$insulindatearr);
        $this->assign('bs',$bsres);
        $this->assign('u',$user);
        $this->assign('date',$date);

        return $this->fetch();

    }


    /*
     * 血糖或者大剂量修改
     *
     *
     * */
    public function checkmodify(){
        $send = input();
        if(empty($send['cid'])){
            $this->error('cid不可以为空');
        }
        $cid = $send['cid'];

        $checkmodel = new Check();
        $cres = $checkmodel->where('cid',$cid)->find();

        if(!empty($send['itemid'])){
            $itemid = $cres['itemid'];
            $itemid = explode(',',$itemid );
            $itemid[1] = $send['itemid'];
            $send['itemid'] = implode(',',$itemid );
        }

        $r = $checkmodel->isUpdate(true)->save($send,['cid'=>$cid]);
        if ($r!=false){
            $this->success('更新成功');
        }else{
            $this->error('更新成功');
        }



    }



    /*
     * 血糖历史记录
     *
     *
     * */
    public function bshistory(){
        $send = input();
        if (empty($send['uid'])){
            $this->error('uid缺失');
        }


        $this->assign('uid',$send['uid']);

        return $this->fetch();


    }



    /*
     * 血糖历史记录
     *
     *
     * */
    public function bshistoryjson(){
        $send = input();
        if (empty($send['uid'])){
            $this->error('uid缺失');

        }
        if (empty($send['key']['sdate'])){
            $send['sdate'] = date('Y-m-d',strtotime('-6days')) ;
        }else{
            $send['sdate'] = $send['key']['sdate'];
        }

        if (empty($send['key']['edate'])){
            $send['edate'] = date('Y-m-d',time()) ;

        }else{
            $send['edate'] = $send['key']['edate'];
        }


        $resarrall = array();//返回的数组

        $uid = $send['uid'];
        //基础率时分段设计
        $btmodel = new Beginningtreatment();
        



        $sdatetime = strtotime($send['sdate']);//开始时间
        $sdatetime =  strtotime(date('Y-m-d',$sdatetime)) ;//0点时间戳

        $edatetime = strtotime($send['edate']);//结束时间
        $edatetime =  strtotime(date('Y-m-d',$edatetime)) ;//0点时间戳

        while($sdatetime<=$edatetime){
            $btttmsg =  $btmodel->getBTByUid($send['uid'],$sdatetime);//起始治疗方案数据，里面有  基础率时分段设计


            $sdate = date('Y-m-d',$sdatetime);//格式化时间

            $checkmodel = new \app\index\model\Check();

//            $bfesum = $checkmodel->getbeforeeatinsulinOfDate($uid, $sdate);//餐前大剂量总量
            $baseinsulin = $btttmsg['baseinsulin'];//基础率总量

            $beforeeatinsulinDate = $checkmodel->getbeforeeatinsulinOfDate($uid,$sdate);//历史记录的餐前大剂量总量
            $temporaryinsulinDate = $checkmodel->gettemporaryinsulinOfDate($uid,$sdate);//历史记录的临时大剂量总量
            $insulinDate = $baseinsulin + $beforeeatinsulinDate + $temporaryinsulinDate;//历史记录的总量



            $bfel = $checkmodel->getBeforeeatingListOfDate($uid, $sdate);//餐前大剂量列表

            $bsl = $checkmodel->getBloodSugarCheckOfDate($uid, $sdate);//血糖列表
            $bsllast = $checkmodel->getBloodSugarCheckOfDate($uid, date('Y-m-d',strtotime('-1day',$sdatetime )) );//血糖列表


            $ipw = $checkmodel->getInsulinPiecewise($btttmsg,$bfel,$bsl,$bsllast);//当天胰岛素分段量
//            dump($bsl);
//            dump($ipw);
//            dump($baseinsulin);
//            dump($beforeeatinsulinDate);
//            dump($temporaryinsulinDate);
//            dump($insulinDate);


            $resarr = array();
            $resarr['date'] = date('m.d',$sdatetime);//时间日期
            $resarr['insulinDate'] = $insulinDate;//胰岛素总量
            /*$resarr['baseandbeforeeatin'] =   array(  // 基础总/餐前总
                'baseinsulin'=>$baseinsulin,//基础率总量
                'beforeeatinsulinDate'=>$beforeeatinsulinDate,//餐前大剂量总量
            );*/
            $resarr['baseandbeforeeatin'] =   $baseinsulin.'/'.$beforeeatinsulinDate;//基础总/餐前总

            $pinyin = new Utf8ToPinyin();//拼音类

            if (!empty($send['itemnamestr'])){//筛选字段
                $itemnamearr = explode(',',$send['itemnamestr'] );//转成数组
                foreach ($ipw as $ii => $iv){
                    if (in_array($ii, $itemnamearr)){//字段筛选
                        $resarr[trimall($pinyin->encode($ii,'all'))] = ($bsl[$ii]['value']?$bsl[$ii]['value']:0)  .' / '. $ipw[$ii]; // 血糖值/胰岛素分段值
                    }
                }
            }else{
                foreach ($ipw as $ii => $iv){
//                    dump($bsl[$ii]['value']);
                    $resarr[trimall($pinyin->encode($ii,'all'))] = ($bsl[$ii]['value']?$bsl[$ii]['value']:0).' / '. $ipw[$ii];
                }
            }



//            dump($resarr);
            $resarrall[]  = $resarr;



            $sdatetime = strtotime('+1day',$sdatetime);//时间戳+1day


        }


        $resjson = '{ "code": 0, "msg": "","count": '.count($resarrall).', "data":'.json_encode($resarrall) .'}';
        echo $resjson;
    }



}